/*
* Copyright (c) 2025 Huawei Device Co., Ltd.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including but not limited to the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to provide persons with access to the Software
* subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGE OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/

import { EventManager } from '../../hooks/eventManager/index';
import { sideBarProperty, SideBarContainerType, ButtonStyle, SideBarPosition, DividerStyle } from '../../types/multi-side-bar/index';
import { defaultConfig } from './default/index';
import { getLengthNum, isValidLength, getFinalLength } from '../../utils/index';
import { CallbackFunc } from '../../types/eventManager';

/**
 * @description 基于web components实现侧边栏组件
 */
export class SideBarComponent extends HTMLElement {
  private _property: string[] = sideBarProperty;
  private _sideBarContainerType: SideBarContainerType = SideBarContainerType.Embed;
  private _showSideBar: boolean | null = null;
  private _autoHide = true;
  private _sideBarWidth = 0;
  private _minSideBarWidth = 0;
  private _maxSideBarWidth = 0;
  private _minContentWidth = 0;
  private _controlButton: ButtonStyle = defaultConfig.controlButton;
  private _showControlButton = true;
  private _sideBarPosition: SideBarPosition = SideBarPosition.Start;
  private _divider: DividerStyle = defaultConfig.divider;

  private _sideBarVisible = true;
  private _sideBarWidthBeforeHidden = 0;
  private _initSideBarWidth = 0;
  private _dividerStrokeWidthBeforeHidden: string | number = 0;
  private _isDragged = false;
  private _isDragging = false;
  private _lastPosition = 0;
  private _currentContainerType: SideBarContainerType = SideBarContainerType.Embed;
  private _contentWidth = 0;
  private _containerWidth = 0;
  private _minCalcContentWidth = 0;
  private _isMounted = false;
  private _resizeObserver: ResizeObserver | null = null;
  private _styleElement: HTMLStyleElement | null = null;
  private _eventManager: EventManager = new EventManager(this);
  private _scopeId = '';
  private _isSideBarStatusChanged = false;
  private _lastSideBarContainerType: SideBarContainerType | null = null;
  private _dividerDom: HTMLElement | null = null;

  readonly MIN_CHILD_COUNT = 1;
  readonly MAX_CHILD_COUNT = 4;

  constructor() {
    super();
  }

  // 创建分割线元素
  private _createDivider(): void {
    const firstChild = this.firstElementChild;
    const dividerElement = document.createElement('div');
    dividerElement.classList.add(`${this._scopeId}-divider`);
    if (firstChild) {
      this.insertBefore(dividerElement, firstChild.nextSibling);
    } else {
      console.error('No valid child elements.');
    }
  }

  // 创建控制按钮元素
  private _createControlButton(): void {
    const lastChild = this.lastElementChild;
    const controlButtonElement = document.createElement('img');
    controlButtonElement.classList.add(`${this._scopeId}-button`);
    if (lastChild) {
      this.insertBefore(controlButtonElement, lastChild.nextSibling);
    } else {
      console.error('No valid child elements.');
    }
  }

  // 设置按钮图片资源
  private _setControlButtonImg(): void {
    const controlButtonElement = this.querySelector(`.${this._scopeId}-button`);
    if (controlButtonElement) {
      controlButtonElement.setAttribute('src', `${this._sideBarVisible ? this._controlButton.icons?.shown : this._controlButton.icons?.hidden}`);
    }
  }

  // 获取容器尺寸
  private _getContainerSize(): void {
    this._containerWidth = this.offsetWidth;
  }

  // 清除过渡效果
  private _clearTransition(): void {
    const timeout = setTimeout(() => {
      this._isSideBarStatusChanged = false;
      clearTimeout(timeout);
    }, 500);
  }

  // 侧边栏隐藏+宽度重新计算
  private _hideSideBarArea(): void {
    this._isSideBarStatusChanged = true;
    this._clearTransition();
    this._sideBarWidthBeforeHidden = this._sideBarWidth;
    this._sideBarWidth = 0;
    this._contentWidth = this._containerWidth;
    this._dividerStrokeWidthBeforeHidden = this._divider.strokeWidth;
    this._divider.strokeWidth = 0;
    this._sideBarVisible = false;
    this._isDragged = true;
    this._eventManager.emit('onVisibleChange', false);
    this._setControlButtonImg();
  }

  // 侧边栏显示+宽度重新计算
  private _showSideBarArea(): void {
    this._isSideBarStatusChanged = true;
    this._clearTransition();
    this._sideBarWidth = this._sideBarWidthBeforeHidden;
    this._divider.strokeWidth = this._dividerStrokeWidthBeforeHidden;
    if (this._currentContainerType === SideBarContainerType.Overlay) {
      this._contentWidth = this._containerWidth;
    } else {
      const remainingSideBarWidth = this._containerWidth - this._minContentWidth;
      if (remainingSideBarWidth <= this._initSideBarWidth && remainingSideBarWidth >= this._minSideBarWidth) {
        this._sideBarWidth = remainingSideBarWidth;
      }
      if (remainingSideBarWidth > this._initSideBarWidth) {
        this._sideBarWidth = this._initSideBarWidth;
      }
      if (remainingSideBarWidth < this._minSideBarWidth && this._containerWidth >= this._minSideBarWidth) {
        this._sideBarWidth = this._minSideBarWidth;
      }
      this._contentWidth = this._containerWidth - getLengthNum(this._divider.strokeWidth.toString()) - this._sideBarWidth;
    }
    this._sideBarVisible = true;
    this._eventManager.emit('onVisibleChange', true);
    this._setControlButtonImg();
  }

  // 分割线拖拽开始回调
  private _dragStartCallback() {
    return (e: TouchEvent): void => {
      this._lastPosition = e.touches[0].clientX;
      this._isDragging = true;
    };
  }

  // 分割线拖拽过程回调
  private _dragMoveCallback() {
    return (e: TouchEvent): void => {
      if (!this._isDragging) {
        return;
      }
      const currentX = e.touches[0].clientX;
      const diff = this._sideBarPosition === SideBarPosition.Start ? currentX - this._lastPosition : this._lastPosition - currentX;
      if (!this._sideBarVisible) {
        this._isDragging = false;
      }
      if (this._sideBarWidth + diff >= this._minSideBarWidth && this._sideBarWidth + diff <= this._maxSideBarWidth) {
        this._lastPosition = currentX;
        this._sideBarWidth = this._sideBarWidth + diff;
        this._initSideBarWidth = this._sideBarWidth;
        if (!this._sideBarVisible || this._currentContainerType === SideBarContainerType.Overlay) {
          this._contentWidth = this._containerWidth;
        } else {
          this._contentWidth = this._containerWidth - getLengthNum(this._divider.strokeWidth.toString()) - this._sideBarWidth;
        }
        this._attachStyles();
      } else if (this._sideBarWidth + diff < this._minSideBarWidth) {
        if (this._autoHide && this._sideBarVisible) {
          this._hideSideBarArea();
          this._attachStyles();
        }
      }
    };
  }

  // 分割线拖拽结束回调
  private _dragEndCallback() {
    return (): void => {
      this._isDragging = false;
      this._isDragged = true;
    };
  }

  // 初始化分割线拖拽事件
  private _setupDragEvents(): void {
    this._dividerDom = this.querySelector(`.${this._scopeId}-divider`);
    this._dividerDom?.addEventListener('touchstart', this._dragStartCallback());
    this._dividerDom?.addEventListener('touchmove', this._dragMoveCallback());
    this._dividerDom?.addEventListener('touchend', this._dragEndCallback());
  }

  // 初始化控制按钮点击事件
  private _setupControlButtonEvent(): void {
    this.querySelector(`.${this._scopeId}-button`)?.addEventListener('click', () => {
      if (this._sideBarVisible) {
        this._hideSideBarArea();
        this._attachStyles();
      } else {
        this._showSideBarArea();
        this._attachStyles();
      }
    });
  }

  // 刷新组件属性和样式
  private _updatComponentState(): void {
    requestAnimationFrame(() => {
      this._getContainerSize();
      this._refreshProperty();
      this._attachStyles();
    });
  }

  // 初始化容器尺寸监听
  private _setupResizeObserver(): void {
    this._resizeObserver = new ResizeObserver(entris => {
      for (const entry of entris) {
        if (entry.target === this) {
          this._updatComponentState();
        }
      }
    });
    this._resizeObserver.observe(this);
  }

  // 自定义元素第一次被连接到文档DOM时被调用
  connectedCallback(): void {
    requestAnimationFrame(() => {
      this._scopeId = this.getAttribute('scope') || '';
      if (this.children.length >= this.MIN_CHILD_COUNT) {
        this._createDivider();
        this._createControlButton();
      }
      this._getContainerSize();
      this._setProperty();
      this._attachStyles();
      this._isMounted = true;
      this._setupDragEvents();
      this._setupControlButtonEvent();
      this._setupResizeObserver();
    });
  }

  // 自定义元素与文档DOM断开连接时被调用
  disconnectedCallback(): void {
    this._dividerDom?.removeEventListener('touchstart', this._dragStartCallback());
    this._dividerDom?.removeEventListener('touchmove', this._dragMoveCallback());
    this._dividerDom?.removeEventListener('touchend', this._dragEndCallback());
    this._resizeObserver?.unobserve(this);
    this._resizeObserver = null;
    this._dividerDom = null;
  }

  // 定义监听属性范围
  static get observedAttributes(): string[] {
    return sideBarProperty;
  }

  // 自定义元素的属性被增加、移除或更改时被调用
  attributeChangedCallback(name: string, oldValue: string | null, newValue: string | null): void {
    if (this._property.includes(name) && oldValue !== newValue && this._isMounted) {
      this._setProperty();
      this._attachStyles();
    }
  }

  // 更新minSideBarWidth
  private _updateMinSideBarWidth(minSideBarWidth: string | null): void {
    if (minSideBarWidth && isValidLength(minSideBarWidth) && getLengthNum(minSideBarWidth) >= 0) {
      this._minSideBarWidth = getFinalLength(minSideBarWidth, this._containerWidth);
    }
  }

  // 更新divider
  private _updateDivider(): void {
    this._divider.strokeWidth = getFinalLength(this._divider.strokeWidth.toString(), this._containerWidth);
    this._divider.startMargin = getFinalLength((this._divider.startMargin || defaultConfig.divider.startMargin).toString(), this._containerWidth);
    this._divider.endMargin = getFinalLength((this._divider.endMargin || defaultConfig.divider.endMargin).toString(), this._containerWidth);
  }

  // 更新minContentWidth
  private _updateMinContentWidth(minContentWidth: string | null): void {
    if (minContentWidth && isValidLength(minContentWidth) && getLengthNum(minContentWidth) >= 0) {
      this._minContentWidth = getFinalLength(minContentWidth, this._containerWidth);
      this._minCalcContentWidth = getFinalLength(minContentWidth, this._containerWidth);
    }
  }

  // 更新sideBarContainerType
  private _updateSideBarContainerType(minSideBarWidth: string | null, minContentWidth: string | null): void {
    if (this._sideBarContainerType === SideBarContainerType.AUTO) {
      let boundaryWidth = 0;
      if (minSideBarWidth && minContentWidth) {
        boundaryWidth = this._minSideBarWidth + this._minCalcContentWidth;
      } else {
        boundaryWidth = Math.max(this._minSideBarWidth + this._minCalcContentWidth, 600);
      }
      if (this._containerWidth < boundaryWidth) {
        this._currentContainerType = SideBarContainerType.Overlay;
      } else {
        this._currentContainerType = SideBarContainerType.Embed;
      }
    } else if (
      this._currentContainerType === SideBarContainerType.Embed && 
      this._showSideBar === null && 
      this._containerWidth < this._minSideBarWidth + this._minCalcContentWidth
    ) {
      this._lastSideBarContainerType = SideBarContainerType.Embed;
      this._currentContainerType = SideBarContainerType.Overlay;
    } else if (
      this._currentContainerType === SideBarContainerType.Overlay &&
      this._lastSideBarContainerType === SideBarContainerType.Embed && 
      this._containerWidth >= this._minSideBarWidth + this._minCalcContentWidth
    ) {
      this._lastSideBarContainerType = null;
      this._currentContainerType = SideBarContainerType.Embed;
    }
  }

  // 更新maxSideBarWidth
  private _updateMaxSideBarWidth(maxSideBarWidth: string | null): void {
    if (!maxSideBarWidth || !isValidLength(maxSideBarWidth) || getLengthNum(maxSideBarWidth) < 0) {
      this._maxSideBarWidth = defaultConfig.maxSideBarWidth;
    } else if (getLengthNum(maxSideBarWidth) > this._containerWidth) {
      this._maxSideBarWidth = this._containerWidth;
    } else {
      this._maxSideBarWidth = getFinalLength(maxSideBarWidth, this._containerWidth);
    }
    if (this._currentContainerType === SideBarContainerType.Embed) {
      this._maxSideBarWidth = Math.min(this._maxSideBarWidth, this._containerWidth - this._minContentWidth);
    }
    this._maxSideBarWidth = Math.max(this._maxSideBarWidth, this._minSideBarWidth);
  }

  // 更新sideBarWidth
  private _updateSideBarWidth(): void {
    if (!this._isDragged && this._currentContainerType === SideBarContainerType.Embed) {
      const sideBarWidth = this.getAttribute('side-bar-width');
      if (sideBarWidth && isValidLength(sideBarWidth) && getLengthNum(sideBarWidth) >= 0) {
        this._sideBarWidth = getFinalLength(sideBarWidth, this._containerWidth);
      }
      this._sideBarWidth = Math.max(Math.min(this._sideBarWidth, this._maxSideBarWidth), this._minSideBarWidth);
    }
  }

  // 更新contentWidth
  private _updateContentWidth(): void {
    if (!this._sideBarVisible || this._currentContainerType === SideBarContainerType.Overlay) {
      this._contentWidth = this._containerWidth;
    } else {
      this._contentWidth = this._containerWidth - getLengthNum(this._divider.strokeWidth.toString()) - this._sideBarWidth;
    }
  }

  // 容器尺寸变化时, 刷新元素属性和组件状态
  private _refreshProperty(): void {
    const minSideBarWidth = this.getAttribute('min-side-bar-width');
    this._updateMinSideBarWidth(minSideBarWidth);

    this._updateDivider();

    const minContentWidth = this.getAttribute('min-content-width');
    this._updateMinContentWidth(minContentWidth);

    this._updateSideBarContainerType(minSideBarWidth, minContentWidth);

    const maxSideBarWidth = this.getAttribute('max-side-bar-width');
    this._updateMaxSideBarWidth(maxSideBarWidth);

    this._updateSideBarWidth();

    this._processSideBarStatus();

    this._updateContentWidth();
  }

  // 元素属性赋值
  private _setProperty(): void {
    // 设置showSideBar的值, 未设置时为null
    const showSideBar = this.getAttribute('show-side-bar');
    this._showSideBar = showSideBar ? showSideBar !== 'false' : null;

    // 设置autoHide的值
    const autoHide = this.getAttribute('auto-hide');
    this._autoHide = autoHide ? autoHide !== 'false' : defaultConfig.autoHide;

    // 设置divider的值
    const divider = this.getAttribute('divider');
    this._divider = divider ? JSON.parse(divider) : defaultConfig.divider;
    this._divider.color = this._divider.color || defaultConfig.divider.color;
    this._divider.strokeWidth = getFinalLength(this._divider.strokeWidth.toString(), this._containerWidth);
    this._divider.startMargin = getFinalLength((this._divider.startMargin || defaultConfig.divider.startMargin).toString(), this._containerWidth);
    this._divider.endMargin = getFinalLength((this._divider.endMargin || defaultConfig.divider.endMargin).toString(), this._containerWidth);

    // 设置宽度值
    this._setWidthProperty();

    // 设置controlButton的值
    const controlButton = this.getAttribute('control-button');
    this._controlButton = controlButton ? JSON.parse(controlButton) : defaultConfig.controlButton;
    this._controlButton.left = this._controlButton.left || defaultConfig.controlButton.left;
    this._controlButton.top = this._controlButton.top || defaultConfig.controlButton.top;
    this._controlButton.width = this._controlButton.width || defaultConfig.controlButton.width;
    this._controlButton.height = this._controlButton.height || defaultConfig.controlButton.height;
    this._controlButton.icons = this._controlButton.icons || defaultConfig.controlButton.icons;
    this._controlButton.icons.shown = this._controlButton.icons.shown || defaultConfig.controlButton.icons.shown;
    this._controlButton.icons.hidden = this._controlButton.icons.hidden || defaultConfig.controlButton.icons.hidden;
    this._setControlButtonImg();

    // 设置showControlButton的值
    const showControlButton = this.getAttribute('show-control-button');
    this._showControlButton = showControlButton ? showControlButton !== 'false' : defaultConfig.showControlButton;
    if (this._showControlButton) {
      this.querySelector(`.${this._scopeId}-button`)?.classList.remove(`${this._scopeId}-button-hidden`);
    } else {
      this.querySelector(`.${this._scopeId}-button`)?.classList.add(`${this._scopeId}-button-hidden`);
    }

    // 设置sideBarPosition的值
    const sideBarPosition = this.getAttribute('side-bar-position');
    this._sideBarPosition = (sideBarPosition || defaultConfig.sideBarPosition) as SideBarPosition;
  }

  // 设置minSideBarWidth
  private _setMinSideBarWidth(minSideBarWidth: string | null): void {
    if (!minSideBarWidth || !isValidLength(minSideBarWidth) || getLengthNum(minSideBarWidth) < 0) {
      this._minSideBarWidth = defaultConfig.minSideBarWidth;
    } else {
      this._minSideBarWidth = getFinalLength(minSideBarWidth, this._containerWidth);
    }
  }

  // 设置minContentWidth 
  private _setMinContentWidth(minContentWidth: string | null): void {
    if (!minContentWidth || !isValidLength(minContentWidth)) {
      this._minContentWidth = 0;
      this._minCalcContentWidth = defaultConfig.minContentWidth;
    } else if (getLengthNum(minContentWidth) < 0) {
      this._minContentWidth = defaultConfig.minContentWidth;
      this._minCalcContentWidth = defaultConfig.minContentWidth;
    } else {
      this._minContentWidth = getFinalLength(minContentWidth, this._containerWidth);
      this._minCalcContentWidth = getFinalLength(minContentWidth, this._containerWidth);
    }
  }

  // 设置sideBarContainerType
  private _setSideBarContainerType(sideBarContainerType: string | null, minSideBarWidth: string | null, minContentWidth: string | null): void {
    if (sideBarContainerType === SideBarContainerType.AUTO) {
      this._sideBarContainerType = sideBarContainerType;
      let boundaryWidth = 0;
      if (minSideBarWidth && minContentWidth) {
        boundaryWidth = this._minSideBarWidth + this._minCalcContentWidth;
      } else {
        boundaryWidth = Math.max(this._minSideBarWidth + this._minCalcContentWidth, 600);
      }
      if (this._containerWidth < boundaryWidth) {
        this._currentContainerType = SideBarContainerType.Overlay;
      } else {
        this._currentContainerType = SideBarContainerType.Embed;
      }
    } else {
      this._sideBarContainerType = (sideBarContainerType || defaultConfig.sideBarContainerType) as SideBarContainerType;
      this._currentContainerType = this._sideBarContainerType;
    }
  }

  // 设置maxSideBarWidth
  private _setMaxSideBarWidth(maxSideBarWidth: string | null): void {
    if (!maxSideBarWidth || !isValidLength(maxSideBarWidth) || getLengthNum(maxSideBarWidth) < 0) {
      this._maxSideBarWidth = defaultConfig.maxSideBarWidth;
    } else if (getLengthNum(maxSideBarWidth) > this._containerWidth) {
      this._maxSideBarWidth = this._containerWidth;
    } else {
      this._maxSideBarWidth = getFinalLength(maxSideBarWidth, this._containerWidth);
    }
    if (this._currentContainerType === SideBarContainerType.Embed) {
      this._maxSideBarWidth = Math.min(this._maxSideBarWidth, this._containerWidth - this._minContentWidth);
    }
    this._maxSideBarWidth = Math.max(this._maxSideBarWidth, this._minSideBarWidth);
  }

  // 设置sideBarWidth
  private _setSideBarWidth(sideBarWidth: string | null): void {
    if (!sideBarWidth || !isValidLength(sideBarWidth) || getLengthNum(sideBarWidth) < 0) {
      this._sideBarWidth = defaultConfig.sideBarWidth;
    } else {
      this._sideBarWidth = getFinalLength(sideBarWidth, this._containerWidth);
    }
    this._sideBarWidth = Math.max(Math.min(this._sideBarWidth, this._maxSideBarWidth), this._minSideBarWidth);
    this._initSideBarWidth = this._sideBarWidth;
  }

  // 计算contentWidth
  private _setContentWidth(): void {
    if (!this._sideBarVisible || this._currentContainerType === SideBarContainerType.Overlay) {
      this._contentWidth = this._containerWidth;
    } else {
      this._contentWidth = this._containerWidth - getLengthNum(this._divider.strokeWidth.toString()) - this._sideBarWidth;
    }
  }

  // 宽度属性赋值逻辑处理
  private _setWidthProperty(): void {
    // 设置minSideBarWidth
    const minSideBarWidth = this.getAttribute('min-side-bar-width');
    this._setMinSideBarWidth(minSideBarWidth);

    // 设置minContentWidth
    const minContentWidth = this.getAttribute('min-content-width');
    this._setMinContentWidth(minContentWidth);

    // 设置sideBarContainerType
    const sideBarContainerType = this.getAttribute('side-bar-container-type');
    this._setSideBarContainerType(sideBarContainerType, minSideBarWidth, minContentWidth);

    // 设置maxSideBarWidth
    const maxSideBarWidth = this.getAttribute('max-side-bar-width');
    this._setMaxSideBarWidth(maxSideBarWidth);

    // 设置sideBarWidth
    const sideBarWidth = this.getAttribute('side-bar-width');
    this._setSideBarWidth(sideBarWidth);

    // 初始化侧边栏状态更新
    this._processSideBarStatus();

    // 计算contentWidth
    this._setContentWidth();
  }

  // Embed状态下, 判断和控制侧边栏折叠展开
  private _controlSideBarStatusEmbed(): void {
    if (this._sideBarVisible) {
      if (this._showSideBar === false) {
        this._hideSideBarArea();
      }
      if (this._showSideBar === null && this._autoHide && this._containerWidth < this._minSideBarWidth + this._minCalcContentWidth) {
        this._hideSideBarArea();
      }
    } else {
      if (this._showSideBar === true) {
        this._showSideBarArea();
      }
      if (this._showSideBar === null && (!this._autoHide || (this._autoHide && this._containerWidth >= this._minSideBarWidth + this._minCalcContentWidth))) {
        this._showSideBarArea();
      }
    }
  }

  // 显隐更新侧边栏宽度
  private _controlSideBarWidth(remainingSideBarWidth: number): void {
    if (this._sideBarVisible) {
      if (remainingSideBarWidth <= this._initSideBarWidth && remainingSideBarWidth >= this._minSideBarWidth) {
        this._sideBarWidth = remainingSideBarWidth;
      }
      if (remainingSideBarWidth > this._initSideBarWidth) {
        this._sideBarWidth = this._initSideBarWidth;
      }
      if (remainingSideBarWidth < this._minSideBarWidth && this._containerWidth >= this._minSideBarWidth) {
        this._sideBarWidth = this._minSideBarWidth;
      }
    }
  }

  // Overlay状态下, 判断和控制侧边栏折叠展开
  private _controlSideBarStatusOverlay(): void {
    const isEmbedBefore = this._showSideBar === null && this._autoHide && this._lastSideBarContainerType === SideBarContainerType.Embed;
    if (this._sideBarVisible && (this._showSideBar === false || isEmbedBefore)) {
      this._hideSideBarArea();
    } else if (!this._sideBarVisible && this._showSideBar !== false && this._lastSideBarContainerType !== SideBarContainerType.Embed) {
      this._showSideBarArea();
    }
  }

  // 初始化/处理侧边栏状态更新
  private _processSideBarStatus(): void {
    if (this._currentContainerType === SideBarContainerType.Embed) {
      const remainingSideBarWidth = this._containerWidth - this._minContentWidth;
      this._controlSideBarStatusEmbed();
      this._controlSideBarWidth(remainingSideBarWidth);
    }
    if (this._currentContainerType === SideBarContainerType.Overlay) {
      this._controlSideBarStatusOverlay();
    }
  }

  // 添加样式
  private _attachStyles(): void {
    if (this._styleElement) {
      this._styleElement.remove();
    }
    const calcSideBarWidth = this._currentContainerType === SideBarContainerType.Embed ? this._sideBarWidth : 
    Math.min(this._sideBarWidth, this._containerWidth);
    const style = document.createElement('style') as HTMLStyleElement;
    style.textContent = `
      .${this._scopeId} {
        display: flex;
        position: relative;
        width: 100%;
        height: 100%;
        box-sizing: border-box;
        flex-direction: ${this._sideBarPosition === SideBarPosition.Start ? 'row' : 'row-reverse'};
        overflow: hidden;
      }
      
      .${this._scopeId} > :first-child {
        width: ${calcSideBarWidth}px;
        min-width: ${calcSideBarWidth}px;
        height: 100%;
        ${this._currentContainerType === SideBarContainerType.Overlay ? 
          'position: absolute; top: 0; left: 0;' : ''
        }
        ${this._isSideBarStatusChanged ? 'transition: width 0.4s ease, min-width 0.4s ease;' : ''}
        overflow: hidden;
      }

      ${this.children.length >= this.MAX_CHILD_COUNT ?
        `.${this._scopeId} > :nth-child(3) {
          width: ${this._contentWidth}px;
          min-width: ${this._minContentWidth}px;
        }` : ''
      }

      .${this._scopeId} .${this._scopeId}-divider {
        width: ${this._divider.strokeWidth}px;
        min-width: ${this._divider.strokeWidth}px;
        height: calc(100% - ${this._divider.startMargin}px - ${this._divider.endMargin}px);
        margin-top: ${this._divider.startMargin}px;
        margin-bottom: ${this._divider.endMargin}px;
        background-color: ${this._divider.color};
        ${this._currentContainerType === SideBarContainerType.Overlay ?
          `position: absolute;
           top: 0;
           left: ${calcSideBarWidth}px;`
          : ''
        }
        transition: width 0.4s ease, ${this._isSideBarStatusChanged ? 'left 0.4s ease' : ''};
      }

      .${this._scopeId} .${this._scopeId}-button {
        position: absolute;
        width: ${this._controlButton.width}px;
        height: ${this._controlButton.height}px;
        ${this._sideBarPosition === SideBarPosition.Start ? 'left' : 'right'}: ${this._controlButton.left}px;
        top: ${this._controlButton.top}px;
      }

      .${this._scopeId} .${this._scopeId}-button-hidden {
        display: none;
      }

      .${this._scopeId} > :nth-child(n+${this.MAX_CHILD_COUNT}):not(:last-child) {
        display: none;
      }
    `;

    this._styleElement = style;
    document.head.appendChild(style);
  }

  registerEvents(callback: CallbackFunc): void {
    this._eventManager.on('onVisibleChange', callback);
  }
}

if (!customElements.get('multi-side-bar-container')) {
  customElements.define('multi-side-bar-container', SideBarComponent);
}